package cn.kailangtu.dataspot.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import java.util.Timer;
import java.util.TimerTask;
import cn.kailangtu.dataspot.MainActivity;
import cn.kailangtu.serialutils.api.SerialPortApi;

public class BootService extends Service {

    private Timer timer;

    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(11, notification);
        }



        // 开启一个定时器，每隔一段时间检查设备状态
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 检查设备状态
                boolean isBootCompleted = isBootCompleted();
                if (isBootCompleted) {
                    // 启动我们的应用
                    Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
                    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(launchIntent);
                }
            }
        }, 0, 20000); // 每隔1秒检查一次设备状态
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // 取消定时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private boolean isBootCompleted() {
        // 检查设备状态，例如通过读取系统属性或查询系统服务
        //return (System.currentTimeMillis() - SerialPortApi.getInstance().getLastReceiveTime()) > 10000;

        return false;
    }


}